<template>
  <div class="app-delivery" style="margin: 0 !important;">
    <div class="filter-containershiping">
      <el-form ref="form" :model="listQuery" label-width="80px">
        <div style="display: flex;flex-wrap: wrap;flex-direction: row;">
          <el-form-item label="后台单号:">
            <el-input v-model.trim="listQuery.xmbzNo" placeholder="请输入后台单号" style="width: 140px;" clearable class="filter-item"
              size="small" />
          </el-form-item>
          <!-- <el-form-item label="平台单号:">
            <el-input v-model.trim="listQuery.platformOrderId" placeholder="请输入平台单号" style="width: 140px;" clearable
              class="filter-item" size="small" />
          </el-form-item> -->
          <el-form-item label="配送时间">
            <!-- <el-date-picker v-model="Launchdate" type="datetimerange" size="small" :default-time="['00:00:00', '23:59:00']"
              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" :clearable='false'>
            </el-date-picker> -->
            <el-date-picker v-model="Launchdate" size='small' type="datetimerange" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm"
              format="yyyy-MM-dd HH:mm" :clearable="false" align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select ref="statusNameRef" v-model="statusName" placeholder="状态" clearable style="width: 180px" class="filter-item" size="small"
              @change="handleStatus" @keydown.native="selectBlur($event)">
              <el-option v-for="item in statusList" :key="item.status" :label="item.statusName" :value="{value:item.status,label:item.statusName}" />
            </el-select>
          </el-form-item>
          <el-form-item label="配送员">
            <el-input v-model="listQuery.delivery" style="width: 140px;" placeholder="请选择配送员" size="small" clearable
              @focus="handleDistributor" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"></el-input>
          </el-form-item>
          <el-form-item label="地区:">
            <el-select ref="mainWarehouseRef" v-model="listQuery.mainWarehouse" placeholder="请选择地区" style="width: 120px" class="filter-item"
              size="small" @change="getmainWarehouseIds" @keydown.native="selectBlur($event)">
              <el-option v-for="item in mainWarehousesList" :key="item.id" :label="item.deptName" :value="{label:item.deptName,value:item.id}" />
            </el-select>
          </el-form-item>
          <el-form-item label="分仓:">
            <el-select ref="barnchWarehousesRef" v-model="barnchWarehousesName" placeholder="请选择仓库 " style="width: 120px" class="filter-item"
              size="small" @change="getbarnchWarehouses" @keydown.native="selectBlur($event)">
              <el-option v-for="item in barnchWarehousesList" :key="item.id" :label="item.name" :value="{label:item.name,value:item.id}" />
            </el-select>
          </el-form-item>
          <el-form-item label="打印状态:">
            <el-select ref="printingStateNameRef" v-model="printingStateName" placeholder="请选择打印状态 " clearable style="width: 150px" class="filter-item"
              size="small" @change="getprintingState" @keydown.native="selectBlur($event)">
              <el-option v-for="item in printstatusList" :key="item.printstatus" :label="item.printstatusName" :value="{value:item.printstatus,label:item.printstatusName}" />
            </el-select>
          </el-form-item>
          <el-form-item label="分配状态">
            <el-select ref="distributionStateRef" v-model="listQuery.distributionState" placeholder="请选择分配状态" clearable style="width: 150px" class="filter-item"
              size="small" @visible-change="getdistributionstate" @keydown.native="selectBlur($event)">
              <el-option v-for="item in distributionStateList" :key="item.dictValue" :label="item.dictValue" :value="item.dictKey" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;">
              <el-row>
                <el-button type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter(Launchdate)"
                  size="small" plain>查询</el-button>
                <!-- <el-button class="filter-item" icon="el-icon-message" @click="handleBatchsigning" size="small" plain onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">批量签收</el-button> -->
                <el-button class="filter-item" icon="el-icon-edit" size="small" plain @click="changeDistributor" style='margin-right: 50px;' onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">批量修改配送员</el-button>
              </el-row>
              <el-row>
                <el-button type="success" class="filter-item" icon="el-icon-download" size="small" plain @click="handlePrintsheet(listQuery.status,multipleSelection)" onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">打印出库单</el-button>
              </el-row>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="mainproduct">
      <el-table :key="tableKey" :data="list" fit highlight-current-row style="width: 100%;"
        @selection-change="handleSelectionChange" :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="20"></el-table-column>
        <el-table-column fixed label="后台订单" prop="id" align="center" min-width="80">
          <template slot-scope="{row}">
            <span>{{ row.xmbzNo }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column fixed label="平台单号" prop="id" align="center" min-width="110">
          <template slot-scope="{row}">
            <span>{{ row.platformOrderId}}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="配送时间" prop="timestamp" min-width="80" align="center">
          <template slot-scope="{row}">
            <span>{{ row.deliveryStartTime.slice(5,16) }}~{{ row.deliveryEndTime.slice(11,16) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" align="center" min-width="50">
          <template slot-scope="{row}">
            <span>{{ row.statusName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调度" prop="dispatcher" align="center" min-width="50">
          <template slot-scope="{row}">
            <span>{{ row.dispatcher }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送员" prop="delivery" align="center" min-width="50">
          <template slot-scope="{row}">
            <span>{{ row.delivery }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地区" prop="mainWarehouse" align="center" min-width="50">
          <template slot-scope="{row}">
            <span>{{ row.mainWarehouse }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库" prop="branchWarehouse" align="center" min-width="50">
          <template slot-scope="{row}">
            <span>{{ row.branchWarehouse }}</span>
          </template>
        </el-table-column>
        <el-table-column label="打印状态" align="center" prop="printingState" min-width="58">
          <template slot-scope="{row}">
            <span v-if="row.printingState==1">未打印</span>
            <span v-else>已打印</span>
          </template>
        </el-table-column>
         <el-table-column label="配送备注" prop="deliveryNotes" align="center" min-width="135">
          <template slot-scope="{row}">
            <span>{{ row.deliveryNotes }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品名称" prop="goodsNameList" align="center" min-width="135">
          <template slot-scope="{row}">
            <span v-for="(item,index) in row.goodsNameList" :key='index'>{{ item }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送地址" prop="receiverAddress" align="center" min-width="135">
          <template slot-scope="{row}">
            <span>{{ row.receiverAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="100">
          <template slot-scope="{row}">
            <el-button v-if=" row.status == 7 ? true : false " type="success" plain size="mini" @click="handleSignfor(row)" style="margin-left: 0;padding: 7px;margin-bottom: 2px;margin-right: 2px;">签收</el-button>
            <el-button size="mini" plain @click="handleDetails(row)" style="margin-left: 0;padding: 7px;margin-bottom: 2px;margin-right: 2px;">查看订单</el-button>
            <el-button v-if="row.status == 4 || row.status == 5 || row.status == 6 || row.status == 7 ? true : false "
              plain size="mini" @click="handleshipping(row)" style="margin-left: 0;padding: 7px;margin-bottom: 2px;">修改配送员</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />
    </div>
    <el-dialog title="我的配送订单查看" :visible.sync="dialogorderdetail">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="订单信息" name="first">
          <div>
            <p><span class="order-messageing">后台单号：</span><span>{{ listdetails.xmbzNo }}</span></p>
            <p><span class="order-messageing">平台单号：</span><span>{{ listdetails.platformOrderId }}</span></p>
            <p><span class="order-messageing">分仓：</span><span>{{ listdetails.branchWarehouse }}</span></p>
            <p><span class="order-messageing">收货人：</span><span>{{ listdetails.receiverName }}</span></p>
            <p><span class="order-messageing">收货电话：</span><span>{{ listdetails.receiverPhone }}</span></p>
            <p><span class="order-messageing">配送时间：</span><span>{{ listdetails.deliveryStartTime }} ~ {{ listdetails.deliveryEndTime?listdetails.deliveryEndTime.slice(11):'' }}</span></p>
            <p><span class="order-messageing">配送备注：</span><span>{{ listdetails.deliveryNotes }}</span></p>
            <p><span class="order-messageing">客户备注：</span><span>{{ listdetails.customerNotes }}</span></p>
            <p><span class="order-messageing">客服备注：</span><span>{{ listdetails.customerServiceNotes }}</span></p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品信息" name="second" style="min-height: 500px;">
          <div>
            <el-row>
              <el-card v-for="(shopitem,shopindex) in shopdetails" :key="shopindex" class="box-card" style="margin-bottom: 20px;">
                <el-col>
                  <div><span class="order-shopmessage">蛋糕：</span><span>{{ shopitem.goodsName }}</span></div>
                  <div><span class="order-shopmessage">价格：</span><span>{{ (shopitem.totalPrice/100).toFixed(2) }}</span></div>
                  <div><span class="order-shopmessage">规格：</span><span>{{ shopitem.goodsSpecs }}</span></div>
                  <div><span class="order-shopmessage">数量：</span><span>{{ shopitem.num }}</span></div>
                  <div><span class="order-shopmessage">状态：</span><span>{{ shopitem.productionStateName }}</span></div>
                  <div><span class="order-shopmessage">祝福语：</span><span>{{ shopitem.blessings }}</span></div>
                </el-col>
              </el-card>
            </el-row>
            <el-col>
              <h3>所选蛋糕总价：￥{{ (this.orderSunPrice/100).toFixed(2) }}</h3>
            </el-col>
          </div>
        </el-tab-pane>
        <el-tab-pane label="配送地址" name="third">
          <div class="map">
            <div class="">
              <p><span class="order-messageing">配送地址：</span><span>{{ listdetails.receiverAddress }}</span></p>
            </div>
            <el-amap vid="amapDemo" id="amapDemo"></el-amap>
          </div>
        </el-tab-pane>
        <el-tab-pane label="订单日志" name="fourth" style="min-height: 500px;">
          <div class="radio" style="margin-bottom: 20px;font-size: 15px;">
            显示方式：
            <el-radio-group v-model="reverse">
              <el-radio :label="true">倒序</el-radio>
              <el-radio :label="false">正序</el-radio>
            </el-radio-group>
          </div>
          <el-timeline :reverse="reverse">
            <el-timeline-item v-for="(item,index) in activities" :key="index" placement="top" style="font-size: 15px;">
              <el-card style="box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);width: 90%;">
                <h4 style="margin-left: 8px;">{{ item.operator }}</h4>
                <h4 v-html='item.action'>{{item.action}}</h4>
                <p style="margin-left: 8px;color: #5e6d82;">{{item.updateTime}}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 查询及修改时使用 -->
    <el-dialog title="选择配送员" :visible.sync="dialogDistributorVisibleFlag" width="width" lock-scroll center>
      <div v-for="(itemmain, key, index) in deliveriesList" :key="index" style="width: 100%;display: flex;border-bottom: 1px solid #efefef;">
        <span style="width: 10%;display: inline-block;line-height: 2;padding: 3px 0;font-size: 14px;font-weight: 550;align-self: center;text-align: center;">{{ key }}</span>
        <div style="width: 90%;display: flex;flex-wrap: wrap;">
          <div v-for="item in itemmain" :key="item.index" style="width: 100px;text-align: center;">
            <div :class="{'grid-content-act': item=== activeIndex}" @click="handledistrorFlag(item)" style="line-height: 2.2;padding: 3px 0;">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div style="display: flex;justify-content: center;margin-top: 20px;">
        <el-button @click="changeSelectDistributorFlag" size="medium" type="primary" plain>选择</el-button>
        <el-button @click="cancelSelectDistributorFlag" size="medium">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择配送员" :visible.sync="dialogDistributorVisible" width="width" lock-scroll center>
      <el-button type="warning" plain size="small" style='margin-bottom: 10px;' v-model="delivery" @click='handledeliverys(deliveriesList)'>清空选中</el-button>
      <div v-for="(itemmain, key, index) in deliveriesList" :key="index" style="width: 100%;" class="deliveriesList">
        <div class="deliveryperson">{{ key }}</div>
        <div class="delivery-item">
          <span v-for="item in itemmain" :key="item.index" :class="{'active': item.isSelected== 1}" @click="handledistror(item,deliveriesList)">{{ item.name }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" v-if="saveflag">
        <el-button type="primary" @click="handelsaveOrder(deliveriesList)">保存</el-button>
      </span>
      <div style="display: flex;justify-content: center;margin-top: 20px;" v-else>
        <el-button @click="cancelSelectDistributor" size="medium">取消</el-button>
        <el-button @click="changeSelectDistributor(deliveriesList)" size="medium" type="primary" plain>分配</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisibleStatus" width="30%">
      <span>打印出库单之前，需要先在筛选框筛选已入库的订单</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleStatusreReset">继 续</el-button>
        <el-button @click="dialogVisibleStatus = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog title="打印出库单预览" :visible.sync="dialogVisiblePrintingpreview" center width='50%'>
      <div id="subOutputRank-print" width='100%'>
        <el-table ref='multipleSelection' :data="multipleSelection" border>
          <el-table-column prop="id" label="后台订单" width="160px"></el-table-column>
          <!-- <el-table-column property="mainWarehouse" label="地区" width="80px"></el-table-column> -->
          <el-table-column property="branchWarehouse" label="仓库" width="80px"></el-table-column>
          <el-table-column label="配送时间" style='width:15%'>
            <template slot-scope="{row}">
              <span>{{ row.deliveryStartTime.slice(5,16) }}~{{ row.deliveryEndTime.slice(11,16) }}</span>
            </template>
          </el-table-column>
          <el-table-column property="goodsNameList" label="商品" style='width:25%'>
            <template slot-scope="{row}">
              <span v-for="(item,index) in row.goodsNameList" :key='index'>{{ item }}</span>
            </template>
          </el-table-column>
          <el-table-column property="deliveryNotes" label="配送备注" style='width:25%'>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisiblePrintingpreview = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handlePrint(multipleSelection)" size="small">打 印</el-button>
      </div>
    </el-dialog>
    <div id="subOutputRank-lodop" style="position: fixed;top: -100%;right: -100%;">
      <table cellspacing="0" style="margin-left: 200px;width: 500px;margin-left: 10px;border-collapse: collapse;border: solid 1px #efefef;padding: 10px;">
        <tr style="width: 100%;">
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 10%;">后台订单</td>
          <!-- <td style="border: solid 1px #efefef;padding: 10px;font-size: 20px;font-weight: 800;width: 15%;">地区</td> -->
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 10%;">仓库</td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 20%;">配送时间</td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 30%;">商品</td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 30%;">配送备注</td>
        </tr>
        <tr v-for="(item,index) in multipleSelection" :key="index" style="width: 100%;">
          <td style="border: solid 1px #efefef;font-size:18px;font-weight: 800;width: 10%;word-wrap:break-word;">{{ item.xmbzNo }}</td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 10%;">{{ item.branchWarehouse }}</td>
          <td style="border: solid 1px #efefef;font-size:18px;font-weight: 800;width: 20%;">{{ item.deliveryStartTime.slice(5,16) }}~{{ item.deliveryEndTime.slice(11,16) }}</td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 30%;">
            <p v-for="(cake,cakeindex) in item.goodsNameList" :key='cakeindex'>{{ cake }}</p>
          </td>
          <td style="border: solid 1px #efefef;font-size: 18px;font-weight: 800;width: 30%;">{{ item.deliveryNotes }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
  var marker, map;
  // import {
  //   deliveriesList,
  // } from "@/api/shop";
  // import getLodop from '@/lodop/LodopFuncs';
  import {
    getOrderDeliveryList, // 我的配送分页条件查询列表
    getOrderInfo, // 查看订单-订单信息
    getOrderGoodsInfo, // 查看订单-商品信息
    getOrderOperateLog, // 日志
    orderSign, // 批量签收(签收)
    deliveries, // 根据城市ID获取上班的配送员
    distributeDeliveryForOrderMyDistribution, // 更改配送员
    batchUpdateOrderPrintingState, // 标记打印出库状态
    distributionstate
  } from "@/api/distribution";
  import {
    getMainWarehouseList,
    getSeparateWarehouseList,
  } from "@/api/orderDispatch";
  import getLodop from '@/lodop/LodopFuncs';
  import {
    query
  } from "@/api/user"; // 查询生产打印机设备
  import Pagination from "@/components/Pagination"; //分页
  import DetailMap from '@/components/pendDetail/map'
  export default {
    name: "myshipping",
    components: {
      Pagination,
      DetailMap
    },
    filters: {},
    data() {
      return {
        tableKey: 0,
        activeIndex: null,
        list: null,
        duanxinList: [],
        total: 0,
        listLoading: true,
        dialogImageUrl: "",
        dialogVisible: false,
        activeName: "first", //生产详情显示状态
        listQuery: {
          deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content, //组织架构ID
          xmbzNo: "", //后台单号
          platformOrderId: "", //平台单号
          orderTimeStart: "", //下单开始时间
          orderTimeEnd: "", //下单结束时间
          receiverPhone: "", //手机
          channel: "", //渠道
          status: "", //订单状态
          deliveryStartTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 00:00:00")
            .toString(), //配送开始时间
          deliveryEndTime: this.dayjs(
              new Date()
            )
            .format("YYYY-MM-DD 23:59:59")
            .toString(), //配送结束时间

          mainWarehouse: "", //总仓
          warehouseId: "", //分仓
          printingState: '',
          page: 1,
          size: 10,
          delivery: ""
        },
        delivery: "",
        listdetails: [],
        shopdetails: [],
        orderDetails: [],
        dialogorderdetail: false,
        dialogDistributorVisible: false,
        deliveriesList: null,
        deptId: {
          deptId: JSON.parse(window.localStorage.getItem("saber-areaId")).content,
        },
        dialogStatus: "",
        downloadLoading: false,
        statusList: [{
            status: 0,
            statusName: '全部（不包含未确认）'
          },
          {
            status: 1,
            statusName: '未确认'
          },
          {
            status: 4,
            statusName: '待生产'
          },
          {
            status: 5,
            statusName: '生产中'
          },
          {
            status: 6,
            statusName: '已入库'
          },
          {
            status: 7,
            statusName: '配送中'
          },
          {
            status: 8,
            statusName: '已签收'
          }
        ],
        getOrderOperateLog: {
          // 订单日志
          orderId: 1
        },
        // 订单日志
        activities: [],
        reverse: false,
        orderdata: {
          orderIds: [], //
          statuss: [],
        },
        value1: "",
        value2: "",
        value3: "",
        getOrderInfoList: {
          orderId: ''
        },
        getOrderGoodsInfoList: {
          orderId: ''
        },
        distributeDeliveryForQuery: { // 给订单分配配送员
          ids: [],
          account: ''
        },
        dialogDistributorVisibleFlag: false,
        //新增地区、仓库
        mainWarehousesList: [],
        barnchWarehousesList: [],
        printstatusList: [{
            printstatus: 1,
            printstatusName: '未打印'
          },
          {
            printstatus: 2,
            printstatusName: '已打印'
          },
        ],
        dialogVisibleStatus: false,
        multipleSelection: [],
        statusName: '',
        dialogVisiblePrintingpreview: false,
        PrintingpreviewList: [],
        mainWarehouseNames: '',
        orderSunPrice: 0, // 订单商品总价
        barnchWarehousesName: '全部',
        Launchdate: [
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 00:00:00")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD 23:59:59")
          .toString(),
        ], //时间
        distributionStateList: [],
        saveflag: false,
        deliveriesIds: '',
        printingStateName: '',
      };
    },
    watch: {
      'dialogorderdetail'() {
        if(this.dialogorderdetail) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
      'dialogDistributorVisibleFlag'() {
        if(this.dialogDistributorVisibleFlag) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
      'dialogDistributorVisible'() {
        if(this.dialogDistributorVisible) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
      'dialogVisiblePrintingpreview'() {
        if(this.dialogVisiblePrintingpreview) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      }
    },
    created() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    mounted() {
      var saberareaIds = JSON.parse(localStorage.getItem('saber-areaId'));
      this.cityareaId = saberareaIds['content'];
      this.getList();
      this.mainWarehouse();
      this.barnchWarehouses();
    },
    methods: {
      getprintingState(data) {
        if (data) {
          this.printingStateName = data.label;
          this.listQuery.printingState = data.value
        } else {
          this.printingStateName = '';
          this.listQuery.printingState = ''
        }
      },
      // 仓库
      getdistributionstate() {
        distributionstate().then(res => {
          this.distributionStateList = res.data.data;
          console.log(this.distributionstateList)
        })
      },
      mainWarehouse() {
        getMainWarehouseList({
          parentId: JSON.parse(window.localStorage.getItem("saber-areaId")).content
        }).then(response => {
          response.data.data.unshift({
            id: '',
            deptName: "全部"
          })
          this.mainWarehousesList = response.data.data;
          this.mainWarehouseIds = response.data.data[0].id;
          this.mainWarehouseNames = response.data.data[0].deptName;
          this.listQuery.mainWarehouse = response.data.data[0].deptName;
        });
      },
      getmainWarehouseIds(data) {
        if (this.listQuery.mainWarehouse == '全部') {
          this.listQuery.mainWarehouse = ''
          this.mainWarehouseNames = ''
          this.mainWarehouseIds = ''
          this.barnchWarehouses();
        } else {
          this.listQuery.mainWarehouse = data.label;
          this.mainWarehouseNames = data.label;
          this.mainWarehouseIds = data.value;
          this.barnchWarehousesName = '全部';
          this.listQuery.warehouseId = "";
          this.barnchWarehouses();
        }
        this.listQuery.warehouseId = "";
      },
      getbarnchWarehouses(data) {
        this.listQuery.warehouseId = data.value;
        this.barnchWarehousesName = data.label;
      },
      barnchWarehouses() {
        getSeparateWarehouseList({
          cityId: this.cityareaId,
          deptId: this.mainWarehouseIds == '' ? '' : this.mainWarehouseIds,
        }).then(response => {
          response.data.data.unshift({
            id: '',
            name: "全部"
          })
          this.barnchWarehousesList = response.data.data;
          this.mainWarehouseIds = response.data.data[0].id;
          this.barnchWarehousesName = response.data.data[0].name;
          this.listQuery.warehouseId = response.data.data[0].id;
        });
      },
      getList() {
        if (this.listQuery.status == '') {
          this.listQuery.status = 0
          this.statusName = '全部（不包含未确认）'
        }
        this.listLoading = true;
        this.listQuery.mainWarehouse = this.mainWarehouseNames;
        this.listQuery.mainWarehouse = this.mainWarehouseNames == '全部' ? '' : this.mainWarehouseNames;
        this.listQuery.deliveryStartTime = this.dayjs(
            this.listQuery.deliveryStartTime
          )
          .format("YYYY-MM-DD HH:mm:00")
          .toString(), //配送开始时间
          this.listQuery.deliveryEndTime = this.dayjs(
            this.listQuery.deliveryEndTime
          )
          .format("YYYY-MM-DD HH:mm:59")
          .toString(), //配送结束时间
          getOrderDeliveryList(this.listQuery).then(response => {
            this.list = response.data.data.rows;

            this.total = response.data.data.total;
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false;
            }, 1.5 * 1000);
            if (this.listQuery.mainWarehouse == '') {
              this.listQuery.mainWarehouse = '全部'
              this.mainWarehouseNames = '';
            }
          });

      },
      // 配送员
      handleDistributor() {
        this.dialogDistributorVisibleFlag = true;
        deliveries(this.deptId).then(res => {
          this.deliveriesList = res.data.data;
        });
      },
      // // 订单状态
      // orderStatus() {
      // orderStatus().then(response => {
      //     this.statusList = response.data.data;
      //     setTimeout(() => {
      //       this.listLoading = false;
      //     }, 1.5 * 1000);
      //   });
      // },
      handleFilter(times) {
        this.listQuery.page = 1;
        if (times) {
          this.listQuery.deliveryStartTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD HH:mm:ss")
            .toString();
          this.listQuery.deliveryEndTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD HH:mm:ss")
            .toString();
        }
        var time1 = Date.parse(this.listQuery.deliveryStartTime);
        var time2 = Date.parse(this.listQuery.deliveryEndTime);
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 31) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          this.listQuery.page = 1;
          this.getList();
        }
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: "操作Success",
          type: "success"
        });
        row.status = status;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      tableRowClassName({
        row
      }) {
        if (row.printingState === 2) {
          return 'warning-row';
        }
        return '';
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.orderdata.orderIds = []
        this.orderdata.status = []
        // console.log('data',val)
        // 获取批量签收的订单数组
        // console.log(val)
        val.forEach(item => {
          this.orderdata.orderIds.push(item.id)
          this.orderdata.status.push(item.status)
        })
      },
      // 批量签收
      handleBatchsigning() {
        if (this.orderdata.orderIds.length == 0) {
          this.$message({
            message: '您还未选择订单，请先选择订单',
            type: 'warning'
          });
        } else if (this.orderdata.orderIds.length > 0) {
          // console.log('this.orderdata.status', this.orderdata.status, this.orderdata.status.indexOf(6))
          if (this.orderdata.status.indexOf(1) > -1 || this.orderdata.status.indexOf(4) > -1 || this.orderdata.status.indexOf(
              5) > -1 || this.orderdata.status.indexOf(8) > -1 || this.orderdata.status.indexOf(6) > -1) {
            this.$message({
              message: '只能签收配送中的订单，请重新选择',
              type: 'warning'
            });
          } else if (this.orderdata.status.indexOf(8) == -1) {
            orderSign(this.orderdata).then((res) => {
              // console.log('签收',res.data.data)
              if (res.data.code == 200) {
                this.$notify({
                  title: "已签收",
                  message: "已签收",
                  type: "success",
                  duration: 2000
                });
                this.orderdata.orderIds = [];
                setTimeout(() => {
                  this.listLoading = false;
                }, 1.5 * 1000);
                this.getList();
                // console.log(this.orderdata.status, 'this.orderdata.status', this.orderdata.status.indexOf(8))
              }
            });
          }
        }
      },
      // 更改配送员
      changeDistributor() {
        this.distributeDeliveryForQuery.ids = this.orderdata.orderIds
        if (this.distributeDeliveryForQuery.ids.length == 0) {
          this.$message({
            message: '您还未选择订单，请先选择订单',
            type: 'warning'
          });
        } else if (this.distributeDeliveryForQuery.ids.length > 0) {
          console.log('this.orderdata.status', this.orderdata.status)
          if (this.orderdata.status.indexOf(1) > -1 || this.orderdata.status.indexOf(8) > -1) {
            this.$message({
              message: '未确认和已签收的订单不能分配给配送员，请重新选择',
              type: 'warning'
            });
          } else if (this.orderdata.status.indexOf(8) == -1) {
            if (this.multipleSelection.length === 0) {
              this.$message.warning("请选择至少一张订单");
              return;
            } else {
              this.dialogDistributorVisible = true;
              let ids = [];
              this.multipleSelection.map(item => {
                ids.push(item.xmbzNo);
              });
              const selectData = {
                xmbzNos: ids.join(','),
                deptId: this.cityareaId
              };
              deliveries(selectData).then(response => {
                this.deliveriesList = response.data.data;
                let isSelectedlist = [];
                for (let warp in this.deliveriesList) {
                  this.deliveriesList[warp].map(item => {
                    if (item.isSelected == '1') {
                      isSelectedlist.push(item)
                    }
                  })
                }
                if (isSelectedlist.length > 0) {
                  this.saveflag = false
                } else {
                  this.saveflag = true
                }
              });
            }
          }
        }

      },
      // 签收
      handleSignfor(row) {
         this.$confirm('此操作将签收, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.orderdata.orderIds=[];
          this.orderdata.orderIds.push(row.id);
        orderSign(this.orderdata).then((res) => {
          if (res.data.code == 200) {
            this.$notify({
              title: "已签收",
              message: "已签收",
              type: "success",
              duration: 2000
            });
            this.orderdata.orderIds = [];
            setTimeout(() => {
              this.listLoading = false;
            }, 1.5 * 1000);
            this.getList();
          }
        });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消签收'
          });
        });

      },
      handleClick(tab) {
        console.log(tab.paneName);
        let arriveCoor = [this.listdetails.longitude, this.listdetails.latitude];
        if (tab.paneName === 'third') {
          var map = new AMap.Map('amapDemo')
          this.addMarker(arriveCoor);
        } else if (tab.paneName === 'second') {
          this.orderSunPrice = 0;
          this.shopdetails.forEach(item => {
            this.orderSunPrice = this.orderSunPrice + item.totalPrice
          })
          // this.orderSunPrice
        }
        // if(){}
      },
      addMarker(arriveCoor) {
        var map = new AMap.Map('amapDemo')
        // 点标记中的文本
        var marker = new AMap.Marker({
          icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: arriveCoor,
          offset: new AMap.Pixel(-13, -30)
        }) // 设置label标签
        // label默认蓝框白底左上角显示，样式className为：amap-marker-label
        marker.setLabel({
          offset: new AMap.Pixel(20, 20), //设置文本标注偏移量
          content: `<div class='info'>${this.listdetails.receiverAddress}</div>`, //设置文本标注内容
          direction: 'top' //设置文本标注方位
        });
        map.add(marker)
        map.setZoomAndCenter(13, arriveCoor)
      },
      // 更改配送员
      handleshipping(row) {
        this.deliveriesIds = row.id;
        // this.distributeDeliveryForQuery.ids[0] = row.id
        this.dialogDistributorVisible = true;
        const selectData = {
          xmbzNos: row.xmbzNo,
          deptId: this.cityareaId
        };
        deliveries(selectData).then(response => {
          this.deliveriesList = response.data.data;
          let isSelectedlist = [];
          for (let warp in this.deliveriesList) {
            this.deliveriesList[warp].map(item => {
              if (item.isSelected == '1') {
                isSelectedlist.push(item)
              }
            })
          }
          if (isSelectedlist.length > 0) {
            this.saveflag = false
          } else {
            this.saveflag = true
          }
        });
        // deliveries(this.deptId).then(res => {
        //   this.deliveriesList = res.data.data;
        // });
      },
      // 生产详情
      handleDetails(row) {
        this.activeName = 'first'
        this.reverse = false;
        // 订单信息
        this.getOrderInfoList.orderId = row.id
        getOrderInfo(this.getOrderInfoList).then(res => {
          this.listdetails = res.data.data
          // console.log('低昂单详情',res.data.data)
        })
        // 商品信息
        this.getOrderGoodsInfoList.orderId = row.id
        getOrderGoodsInfo(this.getOrderGoodsInfoList).then(res => {
          this.shopdetails = res.data.data
          // console.log('shopdetails',res.data.data)
        })
        // 订单日志
        this.getOrderOperateLog.orderId = row.id
        getOrderOperateLog(this.getOrderOperateLog).then(res => {
          this.activities = res.data.data
          // console.log('this.getOrderOperateLog',res.data.data)
        })
        // let arriveCoor = [this.listdetails.longitude, this.listdetails.latitude];
        // 地图
        this.dialogorderdetail = true;
      },
      // 批量设置开始生产
      Startproduction() {},
      createData() {
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
            this.temp.author = "vue-element-admin";
            // createArticle(this.temp).then(() => {
            //   this.list.unshift(this.temp)
            //   this.dialogFormVisible = false
            //   this.$notify({
            //     title: 'Success',
            //     message: 'Created Successfully',
            //     type: 'success',
            //     duration: 2000
            //   })
            // })
          }
        });
      },
      handleproduction() {},
      handledistror(sel, list) {
        this.saveflag = false
        for (let warp in list) {
          list[warp].map(item => {
            item.isSelected = 0
            if (sel.name === item.name) {
              item.isSelected = 1
            }
          })
        }
        this.distributeDeliveryForQuery.account = sel.name;
      },
      // 选择配送员
      handledistrorFlag(item) {
        this.activeIndex = item;
        this.listQuery.delivery = item.name;
      },
      // 选择配送员更改配送员后（选择按钮）更改配送员
      changeSelectDistributor(list) {
        let isSelectedlist = [];
        for (let warp in list) {
          list[warp].map(item => {
            if (item.isSelected == '1') {
              isSelectedlist.push(item)
            }
          })
        }
        if (isSelectedlist.length > 1) {
          this.$message.warning("不能同时分配给多个配送员");
          return;
        }
        let ids = [];
        this.multipleSelection.map(item => {
          ids.push(item.id);
        });
        const selectData = {
          ids: this.deliveriesIds == '' ? ids : [this.deliveriesIds],
          account: this.distributeDeliveryForQuery.account == '' ? isSelectedlist[0].name : this.distributeDeliveryForQuery
            .account
        };
        distributeDeliveryForOrderMyDistribution(selectData).then((res) => {
          if (res.data.code == 200) {
            this.$notify({
              title: "成功",
              message: "修改配送员成功",
              type: "success",
              duration: 2000
            });
            this.dialogDistributorVisible = false;
            this.activeIndex = null;
            this.deliveriesIds = '';
            setTimeout(() => {
              this.listLoading = false;
            }, 1.5 * 1000);
            this.getList();
          }
        });
      },
      handelsaveOrder() {
        let ids = [];
        this.multipleSelection.map(item => {
          ids.push(item.id);
        });
        const selectData = {
          ids: this.deliveriesIds == '' ? ids : [this.deliveriesIds],
          account: ''
        };
        distributeDeliveryForOrderMyDistribution(selectData).then(() => {
          this.$notify({
            title: '提示',
            message: '该订单的配送员已清空',
            type: 'warning'
          });
          this.deliveriesIds = '';
          this.dialogDistributorVisible = false;
          setTimeout(() => {
            this.getList();
          }, 1.5 * 1000);
        });

      },
      // 取消更改配送员后（取消按钮）
      cancelSelectDistributor() {
        this.dialogDistributorVisible = false;
        this.distributeDeliveryForQuery.account = '';
        this.distributeDeliveryForQuery.ids = [];
      },
      // 选择配送员更改配送员后（选择按钮）更改配送员
      changeSelectDistributorFlag() {
        this.dialogDistributorVisibleFlag = false;
      },
      // 取消更改配送员后（取消按钮）
      cancelSelectDistributorFlag() {
        this.dialogDistributorVisibleFlag = false;
        this.distributeDeliveryForQuery.account = '';
        this.distributeDeliveryForQuery.ids = [];
      },
      // 打印出库单
      handlePrintsheet(status) {
        // this.dialogVisibleStatus = true
        // if (status == '' || status == '0' || status == '7' || status == '8' || status == null) {
        //   this.dialogVisibleStatus = true
        // } else
        if (this.multipleSelection.length == 0) {
          this.$message.warning("打印失败，请至少选择一条订单");
        } else if (this.multipleSelection.length >= 20) {
          this.$message.warning("打印失败，一次性最多打印20条订单");
        } else {
          this.dialogVisiblePrintingpreview = true
        }
      },
      handleStatusreReset() {
        this.statusName = '已入库'
        this.listQuery.status = 6
        this.dialogVisibleStatus = false,
          this.handleFilter();
      },
      //状态选择
      handleStatus(data) {
        if (data) {
          this.statusName = data.label;
          this.listQuery.status = data.value
          if (data.value == '6') {
            this.handleFilter();
          }
        } else {
           this.statusName = '全部（不包含未确认）'
          this.listQuery.status = 0
        }


      },
      // handlePrint(id) {
      //   var self = this;
      //   var orderIds = [];
      //   id.map(item => {
      //     orderIds.push(item.id)
      //   })
      //   let subOutputRankPrint = document.getElementById('subOutputRank-print');

      //   let newContent = subOutputRankPrint.innerHTML;
      //   let oldContent = document.body.innerHTML;
      //   document.body.innerHTML = newContent;
      //   window.print();

      //   //打印后事件
      //   const printMedia = window.matchMedia('subOutputRank-print');

      //   if (printMedia.matches) {
      //     batchUpdateOrderPrintingState({
      //       orderIds: orderIds
      //     }).then(response => {
      //       if (response.data.code == '200') {
      //         this.$notify({
      //           title: '打印成功',
      //           message: '请您耐心等待',
      //           type: 'success'
      //         })
      //         self.dialogVisiblePrintingpreview = false;
      //         self.getList();
      //       }
      //     })

      //   } else {
      //     console.log(self, 'self')
      //     this.$message.warning("打印成功已取消");
      //     // self.$notify({
      //     //   title: '打印成功失败',
      //     //   message: '请您耐心等待',
      //     //   type: 'success'
      //     // })
      //   }
      //   document.body.innerHTML = oldContent;
      //   setTimeout(() => {
      //     window.location.reload()
      //   }, 1 * 1000);

      //   return false;
      // },
      handlePrint(id) {
        var self = this;
        var orderIds = [];
        id.map(item => {
          orderIds.push(item.id)
        })
        let formInline = {
          type: 1,
          key: '[1,2]',
          userId: JSON.parse(window.localStorage.getItem("saber-userInfo")).content.account
        }
        query(formInline).then(res => {
          if (res.data.msg == '执行成功') {
            console.log('res.data.data[0].value', res.data.data.length)
            if (res.data.data.length == 0) {
              this.$message.warning("请到系统模块中的打印机设置中添加打印机");
            } else if (res.data.data.length > 0) {
              res.data.data[0].value = `${res.data.data[0].value}`;
              formInline.value = JSON.parse(res.data.data[0].value);
              formInline.print01 = formInline.value[0];
              formInline.print02 = formInline.value[1];
              console.log(res.data.data[0].value, '000', 'formInline.value', formInline.print01);
              const LODOP = getLodop()
              if (LODOP) {
                console.log('res.data.data', document.getElementById('subOutputRank-print').innerHTML)
                LODOP.PRINT_INIT('') //初始化
                LODOP.SET_PRINT_STYLE("FontSize", 12);
                // LODOP.SET_PRINTER_INDEX("POSTEK C168/200s",true); // 增加，需删除
                LODOP.SET_PRINTER_INDEX("NPI46C2BB (HP LaserJet M1536dnf MFP)", true); // 增加，需删除
                // LODOP.SET_PRINT_PAGESIZE(3,'800.6mm','250mm','')
                LODOP.SET_PRINT_PAGESIZE(0, 0, 0, 'A5') //设置横向
                // LODOP.ADD_PRINT_HTM('1%', '1%', '98%', '98%', strFormHtml) //设置打印内容 document.getElementById("d1").innerHTML
                LODOP.ADD_PRINT_HTM('1%', '1%', '100%', '98%', document.getElementById('subOutputRank-lodop').innerHTML) //设置打印内容 document.getElementById("d1").innerHTML
                // console.log('strFormHtml',strFormHtml)
                LODOP.SET_PREVIEW_WINDOW(2, 0, 0, 1000, 800, 0) //设置预览窗口模式和大小
                // LODOP.PREVIEW()
                // if(LODOP.SET_PRINTER_INDEX(0)) LODOP.PRINT(); // 增加，需删除
                // if(LODOP.SET_PRINTER_INDEX("POSTEK C168/200s",true)) LODOP.PRINT(); // 增加，需删除
                LODOP.SET_PRINT_MODE(formInline.print02, true); //这个语句设置网络共享打印机
                LODOP.SET_PRINTER_INDEX(formInline.print02, true); // 增加，需删除
                console.log(LODOP.SET_PRINTER_INDEX(formInline.print02), LODOP.SET_PRINTER_INDEX(formInline.print02,
                  true), 'LODOP.SET_PRINTER_INDEX(`${formInline.print02}`)')
                if (LODOP.SET_PRINTER_INDEX(formInline.print02)) {
                  LODOP.PRINT(); // 增加，需删除
                }
                batchUpdateOrderPrintingState({
                  orderIds: orderIds
                }).then(response => {
                  if (response.data.code == '200') {
                    this.$notify({
                      title: '打印成功',
                      message: '请您耐心等待',
                      type: 'success'
                    })
                    self.dialogVisiblePrintingpreview = false;
                    self.getList();
                  }
                })
              }
            }
          }
        })
      },
      // 清空配送员
      handledeliverys(list) {
        this.saveflag = true
        for (let warp in list) {
          list[warp].map(item => {
            item.isSelected = 0
          })
        }
        this.listQuery.delivery = ''
      },
      // 回车事件
      keyupEnter(){
        if(window.event.keyCode == 13 ){
          this.handleFilter();// 查询事件
        }
      },
      // 选择框回车失焦
      selectBlur(e) {
        if(e.keyCode == 13) {
          this.$refs['mainWarehouseRef'].blur();
          this.$refs['barnchWarehousesRef'].blur();
          this.$refs['statusNameRef'].blur();
          this.$refs['printingStateNameRef'].blur();
          this.$refs['distributionStateRef'].blur();
          e.returnValue = false;
        }
      }
    },
    destroyed() {
      window.removeEventListener("keydown",this.keyupEnter);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown",this.keyupEnter);
    }
  };
</script>
<style lang="scss">
  .el-table .success-row {
    background: #f0f9eb;
  }

  .app-delivery {
    padding: 20px;

    .filter-containershiping {

      // padding-right: 20px;
      .el-form-item {
        margin-bottom: 15px !important;
      }

      .date {
        display: flex;
        // justify-content: space-between;
      }

    }

    .mainproduct {
      padding: 20px;
      background: #fff;

      .warning-row {
        background: #fbfafa;
        color: #333;
      }
    }

    .red {
      color: #ff0000;
    }

    .map {
      width: 700px;
      height: 400px;
    }

    .info {
      margin-bottom: 20px;

      span {
        color: #ff0000;
      }
    }

    .el-row {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .el-col {
      border-radius: 4px;
    }

    .bg-purple-dark {
      background: #99a9bf;
    }

    .bg-purple {
      background: #d3dce6;
      margin-bottom: 10px;
      text-align: center;
      line-height: 36px;
    }

    .bg-purple-light {
      background: #e5e9f2;
    }

    .grid-content {
      border-radius: 4px;
      min-height: 36px;
    }

    .grid-content-act {
      color: #f84f00;
    }

    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }

    .el-form-item {
      .line {
        display: inline-block;
        color: #DCDFE6;
        width: 30px;
      }
    }

    .el-dialog {
      .el-tabs {
        .el-tab-pane {
          div {
            p {
              .order-messageing {
                width: 100px;
                display: inline-block;
                text-align: right;
                margin-right: 10px;
                line-height: 2;
              }
            }

            div {
              .order-shopmessage {
                width: 60px;
                display: inline-block;
                text-align: right;
                margin-right: 10px;
                line-height: 2;
                color: #606266;
              }
            }

            .info {
              padding: 0 6px;
              margin: 0;
            }
          }
        }
      }
    }

    .deliveriesList {
      border-top: 1px solid #ebeef5;
      display: flex;
      line-height: 44px;

      .deliveryperson {
        margin-right: 10px;
      }

      .delivery-item {
        cursor: pointer;
        /* padding-left: 20px; */
        display: flex;
        flex: 1;
        width: 50%;
        flex-wrap: wrap;

        span {
          width: 90px;

          text-align: center;

          &.active {
            width: 77px;
            height: 32px;
            line-height: 17px;
            border-radius: 3px;
            background-color: rgba(238, 248, 232, 1);
            color: rgba(122, 199, 86, 1);
            font-size: 12px;
            text-align: left;
            font-family: Roboto;
            border: 1px solid rgba(122, 199, 86, 1);
            text-align: center;
            line-height: 32px;
            margin-top: 6px;
          }
        }
      }

      &:last-child {
        border-bottom: 1px solid #ebeef5;
      }
    }


    .el-table {
      .cell {
        padding: 0 1px !important;
      }
    }

    table {
      tr {
        td {
          border-right: 0 !important;
        }
      }
    }
  }
</style>
